import React, { useState, useEffect } from 'react';
import AceEditor from 'react-ace';
import ace from 'ace-builds/src-noconflict/ace';
import 'ace-builds/src-noconflict/mode-json';
import 'ace-builds/src-noconflict/theme-github';
import 'ace-builds/src-noconflict/worker-json';

ace.config.set(
  'basePath',
  'https://cdn.jsdelivr.net/npm/ace-builds@1.22.0/src-noconflict/'
);

function JsonEditor({ multiple, onChange, className, placeholder, value }) {
  const [editorValue, setEditorValue] = useState('');

  // 当外部 value 改变时更新编辑器
  useEffect(() => {
    if (value !== undefined) {
      try {
        const stringValue = typeof value === 'string' 
          ? value 
          : JSON.stringify(value, null, 2);
        setEditorValue(stringValue);
      } catch (e) {
        console.error('Error stringifying value:', e);
      }
    }
  }, [value]);

  const handleChange = (newValue) => {
    setEditorValue(newValue);
    try {
      const parsed = JSON.parse(newValue);
      if (multiple) {
        onChange(Array.isArray(parsed) ? parsed : [parsed]);
      } else {
        onChange(parsed);
      }
    } catch (e) {
      // 解析错误时不更新
    }
  };

  return (
    <div className={className}>
      <AceEditor
        mode="json"
        theme="github"
        onChange={handleChange}
        value={editorValue}
        width="100%"
        height="100%"
        placeholder={placeholder}
        setOptions={{
          showPrintMargin: false,
          tabSize: 2,
          useWorker: false
        }}
      />
    </div>
  );
}

export default JsonEditor; 